<template>
    <div>
        <a-card>
            <p slot="title">
                系统管理详情
            </p>
            <div class="syMsg">
                <div class="syMsgTit">配置备份和恢复</div>
                <div class="syMsgCot">
                    <a-button type="primary" @click="backupFun">配置备份</a-button>
                    <!--<a-button type="primary" @click="" class="btnGreen">配置恢复</a-button>-->
                    <div class="importFile" style="margin-left:80px;">
                        <a-button type="primary" class="btnGreen" style="width: 120px !important; margin-left: 0">
                            配置恢复
                        </a-button>
                        <input ref="sendFile" type="file" name="fileName"  @change="importCert($event)" accept=".zip" required />
                    </div>
                </div>
            </div>
            <div class="syMsg">
                <div class="syMsgTit">恢复出厂设置</div>
                <div class="syMsgCot">
                    <a-button type="primary" @click="factoryResetFun">一键恢复</a-button><em>（恢复出厂设置将清除许可信息并重启系统，请谨慎操作！）</em>
                </div>
            </div>
            <div class="syMsg">
                <div class="syMsgTit">系统重启 / 关机</div>
                <div class="syMsgCot">
                    <a-button type="primary" @click="startDeviceFun">系统重启</a-button>
                    <a-button type="primary" @click="closeDeviceFun"  class="btnGreen">系统关闭</a-button> <em>（设备将断电后重新启动！）</em>
                </div>
            </div>
            <div class="syMsg" style="border-bottom: none">
                <div class="syMsgTit">系统升级</div>
                <div class="syMsgCot">
                    <a-form ref="form" :form="form" class="onePageMsg">
                        <div class="handFileBox">
                            <a-input v-model="updateFileName" read-only style="width: 320px; float: left"
                                     disabled :maxlength="100" placeholder="请选择升级tgz文件" />
                            <em class="iconfont cloudwjjk"></em>
                            <a href="javascript:;">
                                <input ref="updateFile" type="file" name="updateFile"
                                       accept=".tgz"
                                       @change="onChangeUpdateFile($event)"
                                       required />
                            </a>
                            <div class="">{{errorMsg}}</div>
                        </div>
                        <a-button type="primary" @click="saveApply">确定升级</a-button>
                    </a-form>

                </div>
            </div>
        </a-card>
        <div class="spinBox" v-if="spinning">{{spinText}}</div>
    </div>
</template>

<script>
    import verify from 'libs/verify'
    import { mapState } from 'vuex'
    export default {
        name: 'sysInit',
        data () {
            return {
                form: this.$form.createForm (this),
                verify,
                spinning: false,
                spinText: '请稍后...',
                id:0,
                updDevInfoFlag:false,
                showArrow:false,
                timer:null,
                updateFile: '',
                updateFileName: '',
                errorMsg:'',
                msg:'',
                signatureData:'',
                showData:{
                    version:'',
                    systemVersion:''
                },
            }
        },
        computed: {
            ...mapState ({
                formStyle: state => state.common.formStyle
            })
        },
        created () {
            let _this = this
            this.init ()
        },
        methods: {
            backupFun(){
                let self = this
                self.$confirm ({
                    title: `是否配置备份?`,
                    okText: '确定',
                    cancelText: '取消',
                    onOk: () => {
                        self.spinning = true
                        self.$get ('/sys/backup').then (res => {
                            if (res.code === 0) {
                                self.$message.success('配置备份命令下发成功，请稍后')
                                self.downLoadJson(res.data)
                            } else {
                                self.spinning = false
                                self.$message.error (res.message)
                            }
                        })
                    }
                })
            },
            downLoadJson(data){
                let blob = ''
                blob =new Blob([this.decodeToArrayBuffer (data.fileContent)])
                let url =URL.createObjectURL(blob)
                let element = document.createElement('a')
                element.style.display = 'none'
                element.href= url
                element.download = data.fileName
                element.click()
            },
            decodeToArrayBuffer(str){
                let bstr = atob(str)
                let length = bstr.length
                let unit8Array = new Uint8Array(length)
                for(let i=0;i<length;i++){
                    unit8Array[i] = bstr.charCodeAt(i)
                }
                return unit8Array.buffer
            },
            /**
             * Function    : importCert
             * Description : 导入证书
             * Input       : none
             * Return      : none
             */
            importCert(e) {
                let _this = this
                let file = e.target.files[0]
                let indexDot = file.name.lastIndexOf('.')
                if (file.name.substr(indexDot + 1, 3) !== 'zip') {
                    _this.$message.warning('请选择.zip')
                    return
                }
                let formData = new FormData()
                let params = {
                    fileName: file.name
                }
               /* formData.append('params', JSON.stringify(params))*/
                formData.append('file', file)
                _this.spinning = true
                _this.$uploadPost('/sys/recoverBackup', formData).then(res => {
                    if (res.code === 0) {
                        _this.$message.success(res.message)
                        _this.init()
                    } else {
                        _this.$message.error(res.message)
                    }
                    if (this.$refs.sendFile !== undefined) {
                        this.$refs.sendFile.value = ''
                    }
                    _this.spinning = false
                })
            },
            factoryResetFun(){
                let self = this
                self.$confirm ({
                    title: `恢复出厂设置将清除许可信息并重启系统，是否确定恢复出厂设置?`,
                    okText: '确定',
                    cancelText: '取消',
                    onOk: () => {
                        self.spinning = true
                        self.$get ('/sys/factoryReset').then (res => {
                            if (res.code === 0) {
                                self.$message.success('恢复出厂设置命令下发成功，请稍后')
                                setTimeout(()=>{
                                    self.spinning = false
                                    sessionStorage.clear()
                                    localStorage.setItem ('interceptorMsg','重启成功后，请重新登录')
                                    window.location.reload();
                                },1000 * 60)   //重启设备后服务也会重新启动需要等待时间
                            } else {
                                self.spinning = false
                                self.$message.error (res.message)
                            }
                        })
                    }
                })
            },
            startDeviceFun(){
                let self = this
                self.$confirm ({
                    title: `是否重启设备?`,
                    okText: '确定',
                    cancelText: '取消',
                    onOk: () => {
                        self.spinning = true
                        self.$get ('/sys/reboot').then (res => {
                            if (res.code === 0) {
                                self.$message.success('重启设备命令下发成功，请稍后')
                                setTimeout(()=>{
                                    self.spinning = false
                                    sessionStorage.clear()
                                    localStorage.setItem ('interceptorMsg','重启成功后，请重新登录')
                                    window.location.reload();
                                },1000 * 60)   //重启设备后服务也会重新启动需要等待时间
                            } else {
                                self.spinning = false
                                self.$message.error (res.message)
                            }
                        })
                    }
                })
            },
            closeDeviceFun(){
                let self = this
                self.$confirm ({
                    title: `是否关闭系统设备?`,
                    okText: '确定',
                    cancelText: '取消',
                    onOk: () => {
                        self.spinning = true
                        self.$get ('/sys/reboot').then (res => {
                            if (res.code === 0) {
                                self.$message.success('关闭系统命令下发成功，请稍后')
                                setTimeout(()=>{
                                    self.spinning = false
                                    sessionStorage.clear()
                                    localStorage.setItem ('interceptorMsg','重启成功后，请重新登录')
                                    window.location.reload();
                                },1000 * 60)   //重启设备后服务也会重新启动需要等待时间
                            } else {
                                self.spinning = false
                                self.$message.error (res.message)
                            }
                        })
                    }
                })
            },
            updateDeviceFun(){
                let _this = this
                this.form.validateFields((err, value) => {
                    if (!err) {
                        let prams = {
                            id:this.id,
                            deviceName:value.deviceName,
                            deviceSerial:value.deviceSerial,
                        }
                        _this.spinning = true
                        _this.$post ('api/hsm/devinfo/updDevInfo',prams).then (res => {
                            _this.spinning = false
                            if (res.code === 0) {
                                _this.$message.success(res.message)
                            } else {
                                _this.$message.error (res.message)
                            }
                        })
                    }
                })

            },
            onChangeUpdateFile ( e ) {
                let _this = this
                if (e.target.files[ 0 ] === undefined) {
                    _this.updateFile = ''
                    _this.updateFileName = ''
                } else {
                    _this.updateFile = e.target.files[ 0 ]
                    _this.updateFileName = e.target.files[ 0 ].name
                    _this.errorMsg = ''
                    let indexDot = _this.updateFileName.lastIndexOf ('.')
                    if (_this.updateFileName.substr (indexDot + 1, 3) !== 'tgz') {
                        _this.errorMsg = '请选择tgz文件'
                        _this.updateFile = ''
                    } else {
                        let size = e.target.files[ 0 ].size
                        let mSize = 1024 * 1024 * 500
                        if (size > mSize) {
                            _this.errorMsg = '请选择小于500M的文件'
                            _this.updateFile = ''
                        }
                    }
                }
                if (this.$refs.updateFile !== undefined) {
                    this.$refs.updateFile.value = ''
                }
            },
            /**
             * Function    : saveApply
             * Description : 用户信息新增、编辑保存
             * Input       : name
             * Return      : none
             */
            saveApply ( e ) {
                e.preventDefault ()
                let _this = this
                if (_this.updateFileName === '') {
                    _this.errorMsg = '请选择tgz文件'
                }
                this.form.validateFields (( err, value ) => {
                    if (!err) {
                        if (_this.errorMsg !== undefined && _this.errorMsg !== '') {
                            return
                        }
                        let formData = new FormData ()
                        _this.spinning = true
                        _this.spinText = '系统文件正在上传中，请稍后...'
                        formData.append ('id', _this.id)
                        formData.append ('updateFile', _this.updateFile)
                        formData.append ('signatureData', value.signatureData)
                        _this.$uploadPost ('/sys/upgrade', formData).then (res => {
                            if (res.code === 0) {
                                _this.$message.success('系统文件上传成功，更新命令下发中，请稍后',10)
                                setTimeout(()=>{
                                    _this.spinning = false
                                    sessionStorage.clear()
                                    localStorage.setItem ('interceptorMsg','软件升级成功后，请重新登录')
                                    // _this.$router.push({
                                    //     name: 'login'
                                    // })
                                    window.location.reload();
                                },1000 * 60 * 3)    //重启设备后服务也会重新启动需要等待时间
                            } else {
                                _this.$message.error (res.message)
                                _this.spinning = false
                                _this.updateFile = ''
                                _this.updateFileName = ''
                                _this.$nextTick (() => {
                                    _this.form.setFieldsValue({ signatureData: '' })
                                })
                                if (_this.$refs.updateFile !== undefined) {
                                    _this.$refs.updateFile.value = ''
                                }
                            }

                        })
                    }
                })

            },
            /**
             * Function    : init
             * Description : 初始化列表
             * Input       : none
             * Return      : none
             */
            init () {
                let _this = this

                this.$get('api/hsm/devinfo/getDevInfo').then(res => {
                    if (res.code === 0) {
                        let data = res.data
                        _this.id = data.id
                        _this.$nextTick (() => {
                            _this.form.setFieldsValue (_this.$pick (data, [ 'deviceName', 'deviceSerial', 'version','systemVersion','deviceStatus','issuerName' ]))
                        })
                    } else {
                        _this.$message.error(res.message)
                    }
                })
            },
        },
        destroyed () {
        }
    }
</script>
<style lang="less">

</style>
